import urllib
import re
import sys
from HTMLParser import HTMLParser
from Episode import EpisodeDetails

class TVRagePrintableParser(HTMLParser):
  title_pattern = re.compile('^\d+ :(?P<series>\d+)x(?P<ep>\d+) - (?P<title>.*)$')

  def __init__(self):
    HTMLParser.__init__(self)
  
  def reset(self):
    HTMLParser.reset(self)
    self.divdepth = 0
    self.episodes = []
    self.series_name = "Unknown Series"
    self.expect_series_name = False
    self.extra_info = {}
    self.start_ep()

  def start_ep(self):
    self.episode_title = None
    self.episode_synopsis = ""
    self.saw_span = 'o' 
    self.extra_info = {}
    self.extra_key = ''
    self.extra_value = ''

  def handle_starttag(self, tag, attrs):
    if tag == 'h2':
      self.expect_series_name = True
    if tag == 'hr':
      if self.episode_title:
        if self.extra_key:
          self._store_extra_info()
        series_number, episode_number, title = self._parse_ep_title(self.episode_title)
        new_episode = EpisodeDetails(self.series_name, series_number, episode_number)
        new_episode.title = title
        new_episode.synopsis = self.episode_synopsis
        new_episode.extra_info = self.extra_info
        self.episodes.append(new_episode)
        self.start_ep()
    if tag == 'div':
      self.divdepth += 1
    if tag == 'span':
      if self.saw_span == 'i':
        self._store_extra_info()
      self.saw_span = 'b' 

  def _store_extra_info(self):
    self.extra_info[self.extra_key.rstrip(':').lower()] = self.extra_value.strip()
    self.extra_key=''
    self.extra_value=''

  def handle_endtag(self, tag):
    if tag == 'div':
      self.divdepth -= 1
    if tag == 'span' and self.saw_span == 'b':
      self.saw_span = 'i'


  def handle_data(self, data):
    if self.divdepth == 3:
      if data.strip():
        if not self.episode_title:
          self.episode_title = data
        else:
          self.episode_synopsis += data
    elif self.expect_series_name:
      if data.endswith('Episode Guide'):
        self.series_name = data.rsplit(' ',2)[0]
        self.expect_series_name = False
    elif self.saw_span == 'b':
      self.extra_key += data
    elif self.saw_span == 'i':
      self.extra_value += data
      

  def _parse_ep_title(self, ep_title):
    match = self.title_pattern.match(ep_title)
    if match:
      title_parts = match.groupdict()
      series = int(title_parts['series'])
      epnum  = int(title_parts['ep'])
      title  = title_parts['title']
      return (series,epnum,title)
    else:
      return (0,0, ep_title)
    

class TVRageScraper(object):
  quickinfo_base = "http://www.tvrage.com/quickinfo.php?show="

  @staticmethod
  def parseQuickInfo(quickinfo):
    return dict(line.strip().split('@',1) for line in quickinfo if '@' in line)
  
  def _quickinfo(self):
    quickinfo_page = self.quickinfo_base + urllib.quote(self.series_name)
    return self.parseQuickInfo(urllib.urlopen(quickinfo_page))
  quickinfo = property(_quickinfo)

  def _printable_page(self):
    return self.quickinfo['Show URL'] + '/printable'
  printable_page = property(_printable_page)

  def __init__(self, series_name):
    self.series_name = series_name
    parser = TVRagePrintableParser()
    parser.feed(urllib.urlopen(self.printable_page).read())
    self.episodes = parser.episodes


def testparser():
  file = open(sys.argv[1])
  parser = TVRagePrintableParser()
  parser.feed(file.read())
  print parser.episodes
  for e in parser.episodes:
    print e
    print
  
def testscraper():
  scraper = TVRageScraper("Mythbusters")
  print scraper.episodes

if __name__ == "__main__":
  testscraper()
  
